<template>
  <div class="avatar-upload">
    <div class="avatar-preview" @click="triggerFileInput">
      <img v-if="avatarUrl" :src="avatarUrl" alt="Avatar" class="avatar-image" />
      <div v-else class="avatar-placeholder">
        <span>点击上传头像</span>
      </div>
    </div>
    <input
      type="file"
      ref="fileInput"
      @change="handleFileChange"
      accept="image/*"
      style="display: none"
    />
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'AvatarUpload',
  props: {
    currentAvatar: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      avatarUrl: this.currentAvatar,
      file: null
    };
  },
  methods: {
    triggerFileInput() {
      this.$refs.fileInput.click();
    },
    async handleFileChange(event) {
      const file = event.target.files[0];
      if (!file) return;

      // 验证文件类型
      if (!file.type.startsWith('image/')) {
        this.$message.error('请上传图片文件');
        return;
      }

      // 验证文件大小（例如限制为2MB）
      if (file.size > 2 * 1024 * 1024) {
        this.$message.error('图片大小不能超过2MB');
        return;
      }

      this.file = file;
      
      // 预览图片
      const reader = new FileReader();
      reader.onload = (e) => {
        this.avatarUrl = e.target.result;
      };
      reader.readAsDataURL(file);

      // 上传文件
      try {
        const formData = new FormData();
        formData.append('file', file);
        
        const response = await axios.post('/api/users/avatar', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        
        this.avatarUrl = response.data.avatar;
        this.$emit('avatar-updated', this.avatarUrl);
        this.$message.success('头像上传成功');
      } catch (error) {
        this.$message.error('头像上传失败');
        console.error('Upload error:', error);
      }
    }
  }
};
</script>

<style scoped>
.avatar-upload {
  display: inline-block;
}

.avatar-preview {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
  border: 2px dashed #d9d9d9;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  color: #8c8c8c;
  font-size: 14px;
  text-align: center;
}

.avatar-preview:hover {
  border-color: #409EFF;
}
</style> 